package com.tedu.firstspringboot.controller;

import com.tedu.firstspringboot.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * 使用当前类处理与用户相关的业务操作
 */

@Controller
public class UserController {


    private static File userDir;//创建一个目录，
    static {//再来一个静态块
        userDir =new File("./users");
        if (!userDir.exists()){
            userDir.mkdirs();
        }
    }



    @RequestMapping("/regUser")
    public void reg(HttpServletRequest request, HttpServletResponse response){//一个给浏览=器发的东西，一个是给他回的东西

       String username= request.getParameter("username");
       String password=request.getParameter("password");
       String name=request.getParameter("name");
       String ageStr=request.getParameter("age");
        System.out.println(username+","+password+","+name+","+ageStr);

        int age=Integer.parseInt(ageStr);//将基本类型转换字节，使用包装类的parseInt
        //第二步2
        User user=new User(username,password,name,age);

        File file=new File(userDir,username+".obj");

        try(FileOutputStream fos=new FileOutputStream(file);
            ObjectOutputStream oos=new ObjectOutputStream(fos);) {

            oos.writeObject(user);
            //利用响应对象，要求浏览器访问注册过程页面，浏览器自发的
            response.sendRedirect("/reg_success.html");



        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
